package su.theravada.jpalireader;

import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Locale;
import java.util.ResourceBundle;
import javax.swing.BorderFactory;

import javax.swing.ComboBoxModel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;

import javax.swing.WindowConstants;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.PopupMenuEvent;
import javax.swing.event.PopupMenuListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.ListModel;
import javax.swing.ListSelectionModel;

import su.theravada.jpalireader.entities.SearchMode;
import su.theravada.jpalireader.util.PaliUtil;
import su.theravada.jpalireader.util.SqlUtil;
import su.theravada.jpalireader.util.UTF8Control;

/**
* This code was edited or generated using CloudGarden's Jigloo
* SWT/Swing GUI Builder, which is free for non-commercial
* use. If Jigloo is being used commercially (ie, by a corporation,
* company or business for any purpose whatever) then you
* should purchase a license for each developer using Jigloo.
* Please visit www.cloudgarden.com for details.
* Use of Jigloo implies acceptance of these licensing terms.
* A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR
* THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED
* LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE.
*/
public class DictionaryPanel extends javax.swing.JPanel {
	private JTextField ctlKeyword;
	private JTextArea ctlTranslation;
	private PaliComboBox ctlPaliCombo;
	private JLabel ctlNoMatch;
	private JScrollPane ctlSearchHistoryScrollPane;
	private JList ctlSearchHistory;
	private JTabbedPane ctlListTabs;
	private JCheckBox ctlIgnoreDiac;
	private JList ctlSearchResults;
	private JButton ctlFind;
	private JComboBox ctlSearchMode;
	private JScrollPane ctlSearchResultsScrollPane; 
	
	public DictionaryPanel() {
		super();
		initGUI();
	}
	
	private void initGUI() {
		try {
            ResourceBundle res_strings = ResourceBundle.getBundle("strings", Locale.getDefault(),new UTF8Control());
            
			this.setPreferredSize(new java.awt.Dimension(641, 196));
			this.setLayout(null);
			{
				ctlKeyword = new JTextField();
				this.add(ctlKeyword);
				ctlKeyword.setBounds(5, 5, 262, 22);
			}
			{				
				ComboBoxModel ctlSearchModeModel = 
					new DefaultComboBoxModel(
							new SearchMode[] { 
									new SearchMode(res_strings.getString("SearchModeAuto"),3),
									new SearchMode(res_strings.getString("BeginsWith"),2) ,
									new SearchMode(res_strings.getString("Contains"),1)
									});
				
				ctlSearchMode = new JComboBox();
				this.add(ctlSearchMode);
				ctlSearchMode.setModel(ctlSearchModeModel);
				ctlSearchMode.setBounds(316, 5, 120, 22);
			}
			{
				ctlFind = new JButton();
				this.add(ctlFind);
				ctlFind.setText(res_strings.getString("Find"));
				ctlFind.setBounds(442, 5, 99, 22);
				ctlFind.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent evt) {
						ctlFindActionPerformed(evt);
					}
				});
			}
			{
				ctlTranslation = new JTextArea();
				this.add(ctlTranslation);
				ctlTranslation.setBounds(273, 59, 361, 114);
				ctlTranslation.setEditable(false);
				ctlTranslation.setWrapStyleWord(true);
				ctlTranslation.setLineWrap(true);
				ctlTranslation.setBorder(BorderFactory.createTitledBorder(""));
			}
			{
				ctlIgnoreDiac = new JCheckBox();
				this.add(ctlIgnoreDiac);
				ctlIgnoreDiac.setText(res_strings.getString("IgnorePaliDiac"));
				ctlIgnoreDiac.setBounds(5, 31, 206, 19);
			}
			{

				ctlPaliCombo = new PaliComboBox();
				this.add(ctlPaliCombo);
				ctlPaliCombo.setBounds(273, 5, 37, 22);
				ctlPaliCombo.setTextField(ctlKeyword);
			}
			{

				ctlSearchHistory = new JList();
				this.add(ctlSearchHistory);
				ctlSearchHistory.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
				ctlSearchHistory.setModel(new DefaultComboBoxModel());
				ctlSearchHistory.addListSelectionListener(new ListSelectionListener() {
					public void valueChanged(ListSelectionEvent evt) {
						ctlSearchHistoryValueChanged(evt);
					}
				});
				
			}
			{
				ctlListTabs = new JTabbedPane();
				this.add(ctlListTabs);
				ctlListTabs.setBounds(5, 59, 262, 135);
				ctlListTabs.setTabPlacement(JTabbedPane.BOTTOM);
				{
					ctlSearchResults = new JList();
					this.add(ctlSearchResults);
					ctlSearchResults.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
					ctlSearchResults.addListSelectionListener(new ListSelectionListener() {
						public void valueChanged(ListSelectionEvent evt) {
							ctlSearchResultsValueChanged(evt);
						}
					});
					
					ctlSearchResultsScrollPane= new JScrollPane();
					ctlListTabs.addTab(res_strings.getString("SearchResults"), null, ctlSearchResultsScrollPane, null);
					ctlSearchResultsScrollPane.getViewport().setView(ctlSearchResults);
					ctlSearchResultsScrollPane.setBounds(384, 197, 201, 132);
				}
				{
					ctlNoMatch = new JLabel();
					this.add(ctlNoMatch);
					ctlNoMatch.setText(res_strings.getString("NoMatches"));
					ctlNoMatch.setVisible(false);
					ctlNoMatch.setForeground(new java.awt.Color(255,0,0));
					ctlNoMatch.setBounds(253, 32, 329, 17);
				}
				{
					ctlSearchHistoryScrollPane = new JScrollPane();
					ctlListTabs.addTab(res_strings.getString("SearchHistory"), null, ctlSearchHistoryScrollPane, null);
					ctlSearchHistoryScrollPane.setBounds(229, 222, 267, 152);
					ctlSearchHistoryScrollPane.getViewport().setView(ctlSearchHistory);
				}
			}

	    	JPopupMenu objPopupMenu=new JPopupMenu();	    
		    JMenuItem ctlEdit=new JMenuItem(res_strings.getString("Edit"));
		    JMenuItem ctlDelete= new JMenuItem(res_strings.getString("Delete"));
		    JMenuItem ctlAddNew= new JMenuItem(res_strings.getString("AddNew"));
		    objPopupMenu.add(ctlEdit);
		    objPopupMenu.add(ctlDelete);
		    objPopupMenu.add(ctlAddNew);
			ctlSearchResults.setComponentPopupMenu(objPopupMenu);
			objPopupMenu.addPopupMenuListener(new PopupMenuListener() {

				@Override
				public void popupMenuCanceled(PopupMenuEvent arg0) {}

				@Override
				public void popupMenuWillBecomeInvisible(PopupMenuEvent arg0) {}

				@Override
				public void popupMenuWillBecomeVisible(PopupMenuEvent arg0) {
					OnpopupMenuWillBecomeVisible(arg0);					
				}});
			
			ctlEdit.addActionListener(new ActionListener() {
				@Override
				public void actionPerformed(ActionEvent arg0) {
					OnDictionaryEdit(arg0);					
				}				
			});
			
			ctlDelete.addActionListener(new ActionListener() {

				@Override
				public void actionPerformed(ActionEvent e) {
					OnDictionaryDelete(e);						
				}});
			
			ctlAddNew.addActionListener(new ActionListener() {
				
				@Override
				public void actionPerformed(ActionEvent e) {
					OnDictionaryAddNew(e);						
				}
			});
			
			ctlKeyword.addKeyListener(new KeyListener() {

				@Override
				public void keyPressed(KeyEvent arg0) {}

				@Override
				public void keyReleased(KeyEvent arg0) {
					if(arg0.getKeyCode()==KeyEvent.VK_ENTER)
						ctlFindActionPerformed(null);
				}

				@Override
				public void keyTyped(KeyEvent arg0) {}				
			});
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private void OnpopupMenuWillBecomeVisible(PopupMenuEvent arg0)
	{
		ResourceBundle res_strings = ResourceBundle.getBundle("strings", Locale.getDefault(),new UTF8Control());
		
		JPopupMenu objPopupMenu=(JPopupMenu)arg0.getSource();
		for (Component child : objPopupMenu.getComponents()) 	
		{
			JMenuItem objItem=(JMenuItem)child;
			if(ctlSearchResults.getSelectedValue()==null)
				objItem.setEnabled(!(objItem.getText()==res_strings.getString("Edit") ||
						objItem.getText()==res_strings.getString("Delete")));
			else
				objItem.setEnabled(true);			
		}
	}
	
	
	public void Lookup(String strKeyword)
	{	
		ctlKeyword.setText(strKeyword);
		
		if(!strKeyword.isEmpty())
		{
			ResultSet rs = null;
	        PreparedStatement ps = null;
			
			try
			{				
				String strName=strKeyword.toLowerCase();
				if(ctlIgnoreDiac.isSelected())
					strName=PaliUtil.ConvertDiac(strName);
				
				if(ctlIgnoreDiac.isSelected())			
					ps=MainWindow.getDBConnection().prepareStatement("SELECT entryid, keyword, \"Translation\" FROM dictionarycontent WHERE keywordnodiac LIKE ?");													
				else
					ps=MainWindow.getDBConnection().prepareStatement("SELECT entryid, keyword, \"Translation\" FROM dictionarycontent WHERE keyword LIKE ?");			
				
				int SearchMode=((SearchMode)ctlSearchMode.getSelectedItem()).getId();
				
				boolean bSearchSuccessful=false;
				if(SearchMode==3)
				{
					int SearchTermLength=strName.length()+1;
					while(SearchTermLength>0)
					{
						ps.setString(1, strName.substring(0,SearchTermLength-1)+'%');    				
						rs=ps.executeQuery();
						if(rs.next())
						{
							bSearchSuccessful=true;
							break;
						}
						
						SearchTermLength--;
					}					
				}
				else
				{
					if(SearchMode==1)				
			            strName='%'+strName+'%';				
					else							          
			            strName=strName+'%';
					
					ps.setString(1, strName);    				
					rs=ps.executeQuery();
					bSearchSuccessful=rs.next();
				}				

				ArrayList<LookupResult> arrResults=new ArrayList<LookupResult>();
				
				if(bSearchSuccessful)
					do
					{
						arrResults.add(new LookupResult(rs.getInt("entryid"),
								rs.getString("keyword"),rs.getString("Translation")));
					}		
					while(rs.next());
					
				ListModel ctlSearchResultsModel = new DefaultComboBoxModel(arrResults.toArray());
				ctlSearchResults.setModel(ctlSearchResultsModel);	
				
				ctlTranslation.setText("");
				ctlNoMatch.setVisible(arrResults.isEmpty());
				
				if(arrResults.size()==1)
					ctlSearchResults.setSelectedIndex(0);
			}
			catch(SQLException sqle)
			{		
				SqlUtil.ReportSQLException(sqle);
			}
			catch(Exception ex)
			{		
				ex.printStackTrace();					
			}
			finally
			{
				SqlUtil.ClosePreparedStatement(ps);
				SqlUtil.CloseResultSet(rs);		
			}
			
		}				
	}
		
	private void ctlFindActionPerformed(ActionEvent evt) 
	{
		Lookup(ctlKeyword.getText());
	}
	
	private void ctlSearchResultsValueChanged(ListSelectionEvent evt) 
	{
		LookupResult objResult=(LookupResult)ctlSearchResults.getSelectedValue();
		if(objResult!=null)
		{
			ctlTranslation.setText(objResult.getTranslation());
			DefaultComboBoxModel objModel=(DefaultComboBoxModel)ctlSearchHistory.getModel();
			if(objModel.getIndexOf(objResult)<0)
				objModel.insertElementAt(objResult, 0);
		}
	}

	private void ctlSearchHistoryValueChanged(ListSelectionEvent evt)
	{
		LookupResult objResult=(LookupResult)ctlSearchHistory.getSelectedValue();
		if(objResult!=null)
		{
			ctlTranslation.setText(objResult.getTranslation());
		}
	}
	
	private void OnDictionaryEdit(ActionEvent arg0)
	{
		LookupResult objResult=(LookupResult)ctlSearchResults.getSelectedValue();
		DictionaryEditDlg objDlg=new DictionaryEditDlg((JFrame)getTopLevelAncestor(),objResult.getEntryId());
		objDlg.setLocationRelativeTo(null);
		objDlg.setVisible(true);
		
		Lookup(ctlKeyword.getText());
	}
	
	private void OnDictionaryDelete(ActionEvent arg0)
	{
        ResourceBundle res_strings = ResourceBundle.getBundle("strings", Locale.getDefault(),new UTF8Control());
        
        Object[] options = {res_strings.getString("Yes"),
        		res_strings.getString("No")};
        
        int nDialogResult = JOptionPane.showOptionDialog(getTopLevelAncestor(),
				res_strings.getString("SureDeleteItem"),
				res_strings.getString("Confirm"),
			    JOptionPane.YES_NO_OPTION,
			    JOptionPane.QUESTION_MESSAGE,
			    null,     //do not use a custom Icon
			    options,  //the titles of buttons
			    options[0]);
		
        if(nDialogResult==JOptionPane.YES_OPTION)
        {    
	        PreparedStatement ps = null;
	        
	        try
	        {
	    		LookupResult objResult=(LookupResult)ctlSearchResults.getSelectedValue();
	       		ps=MainWindow.getDBConnection().prepareStatement("DELETE FROM dictionarycontent WHERE entryid=?");
	        	
	        	ps.setInt(1, objResult.getEntryId());
	        	
				ps.execute();  
				
				Lookup(ctlKeyword.getText());
	        }
			catch(SQLException sqle)
			{		
				SqlUtil.ReportSQLException(sqle);
			}
			catch(Exception ex)
			{		
				ex.printStackTrace();					
			}
			finally
			{
				SqlUtil.ClosePreparedStatement(ps);	
			}	
        }
	}
	
	private void OnDictionaryAddNew(ActionEvent arg0)
	{
		DictionaryEditDlg objDlg=new DictionaryEditDlg((JFrame)getTopLevelAncestor());
		objDlg.setLocationRelativeTo(null);
		objDlg.setVisible(true);
	}
	
	private class LookupResult
	{
		private int _entryId;
		private String _keyword;
		private String _translation;
		
		public LookupResult(int entryId,String keyword,String translation)
		{
			_entryId=entryId;
			_keyword=keyword;
			_translation=translation;
		}
		
		public String toString()
		{
			return _keyword;
		}
		
		public String getTranslation()
		{
			return _translation.replace("[c]", "").replace("[/c]", "\r\n");
		}
		
		public int getEntryId()
		{
			return _entryId;
		}
	}
	
}
